package com.strong.task1.mr;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;

public class WordSortDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        File file = new File("d:/test/task/output");
        FileUtils.deleteDirectory(file);

        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        job.setJarByClass(WordSortDriver.class);

        job.setMapperClass(WordSortMapper.class);
        job.setReducerClass(WordSortReducer.class);

        //将多个小文件合并成一个文件
        job.setInputFormatClass(CombineTextInputFormat.class);
        CombineTextInputFormat.setMaxInputSplitSize(job, 1024 * 1024);

        //mapper output: key and value
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        //测试代码
        ClassLoader classLoader = WordSortDriver.class.getClassLoader();
        String file1 = classLoader.getResource("1.txt").getPath();
        String file2 = classLoader.getResource("2.txt").getPath();
        String file3 = classLoader.getResource("3.txt").getPath();

        FileInputFormat.setInputPaths(job, new Path(file1), new Path(file2), new Path(file3));
        FileOutputFormat.setOutputPath(job, new Path("d:/test/task/output"));

        boolean ret = job.waitForCompletion(true);
        System.exit(ret ? 0 : 1);
    }
}
